package controllers

import (
	"dmsv/agent"
	"dmsv/ws"
	beego "github.com/beego/beego/v2/adapter"
	"github.com/beego/beego/v2/core/logs"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

type WebSocketController struct {
	beego.Controller
}

func (this *WebSocketController) URLMapping() {
	this.Mapping("conn", this.Listen)
}

// @Title
// @Description ws连接
// @router /conn [get]
func (c *WebSocketController) Listen() {

	upgrader := websocket.Upgrader{
		ReadBufferSize:  512,
		WriteBufferSize: 512,

		// 解决跨域问题
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	newClient, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		logs.Error(err)
		return
	}

	go func() {
		nws, err := ws.NewRegister(newClient)
		if err != nil {
			newClient.WriteJSON(MakeSysErrCode(err.Error()))
			newClient.Close()
		} else {
			if agent.AddAgentWsChannel(nws) != nil {
				nws.SendMessage(ServiceNeedSignIn)
				newClient.Close()
			} else {
				go func() {
					for {
						err = agent.DetectSipReg(nws.SipAcct)
						if err != nil {
							if nws.SendMessage(ServiceNeedRegister) != nil {
								break
							}
							logs.Debug("[%v]坐席未找到，发送消息:%v", nws.SipAcct, ServiceNeedRegister)
						} else {
							break
						}

						time.Sleep(30 * time.Second)
					}
				}()
			}
		}
	}()
}
